// 商品详情并加入购物车
export default function(){
    function carts(){

    }
    $.extend(carts.prototype,{
        init : function(){
            this.down   = $(".decrease");
            this.up     = $(".increase");
            this.add_btn= $(".add-cart-btn");
            this.sum    = $("input[name='amount']");
            var customNum  = $("input[name='amount']").attr("value");
            this.count     = Number(customNum); 
            // console.log(this.count);
            this.cartNum = $(".cartnum");//购物车
            this.down.on("click",$.proxy( this.reduceGoodsNum ,this ));//数量减
            this.up.on("click",$.proxy( this.addGoodsNum , this));//数量加
            this.add_btn.on("click" , $.proxy( this.addCart,this));//加入购物车
            this.sumCartNum();
        },
        reduceGoodsNum : function(){
            this.count--;
            if(this.count < 1){
                this.count = 1
            }
            $(this.sum).attr("value",this.count);
        },
        addGoodsNum : function(){
            this.count++;
            $(this.sum).attr("value",this.count);
        },
        addCart : function(){
            var id = location.hash.substring(1);
            this.save(id);
        },
        save : function(data){//商品id
            var count = this.count;
            var ls = localStorage.getItem("goods");
            if(ls == null){
                var arr = [{
                    id : data ,
                    count : count
                }];
                localStorage.setItem("goods",JSON.stringify(arr));
            }
            else{
                var la = JSON.parse(ls);
                var has_same_id = false;
                $.each(la,function(index,item){
                    if(item.id == data){
                        item.count = Number(item.count)+count;
                        has_same_id = true;
                    }
                })
                if(!has_same_id){
                    la.push({
                        id : data ,
                        count : count
                    })
                }
                localStorage.setItem("goods",JSON.stringify(la));
            }
            this.sumCartNum();
        },
        // 购物车数量
        sumCartNum : function(){
            var ls = localStorage.getItem("goods");
            var la = JSON.parse(ls === null ? "[]" : ls);
            var sum = 0;
            la.forEach( function(item){
                sum += Number(item.count);
            })
            $(this.cartNum).html(sum);
            return sum;
        }
    })
    return new carts();
}